import { Model, DataTypes, Optional } from 'sequelize';
import sequelize from '@/config/database';

// 定义任务属性接口
interface JobAttributes {
  jobId: number;
  jobName: string;
  jobGroup: string;
  invokeTarget: string;
  cronExpression: string;
  misfirePolicy?: string;
  concurrent?: string;
  status?: string;
  createBy?: string;
  createTime?: Date;
  updateBy?: string;
  updateTime?: Date;
  remark?: string;
}

// 创建时可选的字段
interface JobCreationAttributes extends Optional<JobAttributes, 'jobId'> {}

// 任务模型类
class Job extends Model<JobAttributes, JobCreationAttributes> implements JobAttributes {
  public jobId!: number;
  public jobName!: string;
  public jobGroup!: string;
  public invokeTarget!: string;
  public cronExpression!: string;
  public misfirePolicy?: string;
  public concurrent?: string;
  public status?: string;
  public createBy?: string;
  public createTime?: Date;
  public updateBy?: string;
  public updateTime?: Date;
  public remark?: string;

  // 时间戳
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // 获取任务唯一标识
  public getJobKey(): string {
    return `${this.jobGroup}:${this.jobName}`;
  }

  // 检查任务状态是否正常
  public isActive(): boolean {
    return this.status === '0';
  }
}

Job.init(
  {
    jobId: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      autoIncrement: true,
      field: 'job_id'
    },
    jobName: {
      type: DataTypes.STRING(64),
      allowNull: false,
      field: 'job_name'
    },
    jobGroup: {
      type: DataTypes.STRING(64),
      allowNull: false,
      field: 'job_group'
    },
    invokeTarget: {
      type: DataTypes.STRING(500),
      allowNull: false,
      field: 'invoke_target'
    },
    cronExpression: {
      type: DataTypes.STRING(255),
      allowNull: false,
      field: 'cron_expression'
    },
    misfirePolicy: {
      type: DataTypes.STRING(1),
      defaultValue: '0',  // 0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行
      field: 'misfire_policy'
    },
    concurrent: {
      type: DataTypes.STRING(1),
      defaultValue: '1',  // 0=允许,1=禁止
      field: 'concurrent'
    },
    status: {
      type: DataTypes.STRING(1),
      defaultValue: '0',  // 0=正常,1=暂停
      field: 'status'
    },
    createBy: {
      type: DataTypes.STRING(64),
      field: 'create_by'
    },
    createTime: {
      type: DataTypes.DATE,
      field: 'create_time'
    },
    updateBy: {
      type: DataTypes.STRING(64),
      field: 'update_by'
    },
    updateTime: {
      type: DataTypes.DATE,
      field: 'update_time'
    },
    remark: {
      type: DataTypes.STRING(500)
    }
  },
  {
    sequelize,
    tableName: 'sys_job',
    timestamps: true,
    createdAt: 'createTime',
    updatedAt: 'updateTime',
    hooks: {
      beforeCreate: (job: Job) => {
        if (!job.createTime) {
          job.createTime = new Date();
        }
      },
      beforeUpdate: (job: Job) => {
        job.updateTime = new Date();
      }
    }
  }
);

export default Job; 